package org.apache.dolphinscheduler.api.utils;

import java.lang.reflect.Field;
import java.util.Objects;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

/**
 * 字典格式化转换处理
 */
public class ExcelDictConvert implements Converter<Object> {

    @Override
    public Class<Object> supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public WriteCellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty,
                                                    GlobalConfiguration globalConfiguration) {
        if (Objects.isNull(object)) {
            return new WriteCellData<>("");
        }
        ExcelDictFormat anno = getAnnotation(contentProperty.getField());
        String value = String.valueOf(object);
        String label;
        label = ExcelUtil.convertByExp(value, anno.readConverterExp(), anno.separator());
        return new WriteCellData<>(label);

    }

    private ExcelDictFormat getAnnotation(Field field) {
        if (field.isAnnotationPresent(ExcelDictFormat.class)) {
            // 获取Annotation对象
            return field.getAnnotation(ExcelDictFormat.class);
        }
        return null;
    }
}
